package com.boesch.electroOffice.dataaccess.mapper;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.dataaccess.dao.IdentifierDao;
import com.boesch.electroOffice.model.electroOffice.WorkingHour;
import com.boesch.electroOffice.utils.DateUtils;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

/**
 * This class mappes the rows from database to a WorkingHour object.
 * 
 * @author Ralph Koster
 *
 */
public class WorkingHourMapper implements RowMapper<WorkingHour>, Serializable {

	private static final long serialVersionUID = 5580293123147907469L;
	private static final Log log = LogFactoryUtil.getLog(WorkingHourMapper.class);

	private IdentifierDao identifierDao;

	public WorkingHourMapper(IdentifierDao identifierDao) {
		this.identifierDao = identifierDao;
	}

	/**
	 * Mapps all rows from database to a WorkingHour object.
	 * 
	 * @see org.springframework.jdbc.core.RowMapper
	 */
	public WorkingHour mapRow(ResultSet rs, int rowNum) throws SQLException {
		WorkingHour workingHour = new WorkingHour();
		try {
			workingHour.setId(rs.getInt("Id_pk"));
			workingHour.setWorkdate(DateUtils.convertDateToLocalDate(rs.getDate("Workday")));
			workingHour.setHours(rs.getDouble("Hours"));
			workingHour.setAppointmentId(rs.getInt("AppointmentId"));
			workingHour.setLrUserId(rs.getLong("LrUserId"));
			workingHour.setWorkingIdentifier(identifierDao.getIdentifierById(rs.getInt("ToolIdentifierId")));
			workingHour.setCreatedBy(rs.getString("Createdby"));
			workingHour.setCreatedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Createdat")));
			workingHour.setModifiedBy(rs.getString("Modifiedby"));
			workingHour.setModifiedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Modifiedat")));
			workingHour.setVersion(rs.getInt("Version"));
		} catch (IllegalDataAccessException e) {
			log.error("Failed to load identifier with id: " + rs.getInt("ToolIdentifierId"), e);
			throw new SQLException("Failed to load identifier!", e);
		}
		return workingHour;
	}
}
